const __UPLOAD_URL = document.getElementById('__UPLOAD_URL').getAttribute('value');
const __PATH = document.getElementById('__PATH').getAttribute('value');
const __ROUTE_FROM = document.getElementById('__ROUTE_FROM').getAttribute('value');


function formatFileSize(fileSize) {
    if (fileSize < 1024) {
        return fileSize + 'B';
    } else if (fileSize < (1024 * 1024)) {
        var temp = fileSize / 1024;
        temp = temp.toFixed(2);
        return temp + 'KB';
    } else if (fileSize < (1024 * 1024 * 1024)) {
        var temp = fileSize / (1024 * 1024);
        temp = temp.toFixed(2);
        return temp + 'MB';
    } else {
        var temp = fileSize / (1024 * 1024 * 1024);
        temp = temp.toFixed(2);
        return temp + 'GB';
    }
}
function uploadFrame(name, fragment, seq, total, onSuccess, onFail) {
    let xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = () => {
        if (xhttp.readyState == 4) { 
            let code = xhttp.status;
            if (code == 200) {
                if (onSuccess) {
                    onSuccess();
                }
            } else {
                if (onFail) {
                    let resp = JSON.parse(xhttp.responseText);
                    onFail(resp['msg']);
                }
            }
        }
    }
    xhttp.open("POST", __UPLOAD_URL, false);
    let json = {
        filename: name,
        bytes: fragment,
        seq: seq,
        total: total,
        rf: __ROUTE_FROM,
        path: __PATH
    };
    let str = JSON.stringify(json);
    xhttp.send(str);
}
function uploadFile(fileObj, frameSize, onProgressChanged, onSuccess, onFail) {
    const reader = new FileReader();
    reader.readAsBinaryString(fileObj);
    reader.onload = function () {
        let data = this.result;
        let total = Math.floor(data.length / frameSize);
        if (data.length % frameSize !== 0) {
            total += 1;
        }
        let id = 0;
        let nextFrame = true;
        let fragmentInterval = setInterval(() => {
            if (id >= total) {
                clearInterval(fragmentInterval);
                fragmentInterval = null;
                return;
            }
            if (nextFrame) {
                nextFrame = false;
                let fragment;
                if (id === total - 1) {
                    fragment = data.slice(id * frameSize, data.length);
                } else {
                    fragment = data.slice(id * frameSize, (id + 1) * frameSize);
                }
                uploadFrame(fileObj.name, fragment, id + 1, total, 
                    () => {
                        nextFrame = true;
                        onProgressChanged(Math.round(10000*(id+1)/total)/100);
                        if (id + 1 == total) {
                            clearInterval(fragmentInterval);
                            fragmentInterval = null;
                            onSuccess();
                        }
                    }, (reason) => {
                        clearInterval(fragmentInterval);
                        fragmentInterval = null;
                        onFail(reason);
                    }
                );
                id++;
            }
        }, 5);
    }
}
const btnUploadDlg = document.getElementById('btn-upload-dlg');
const domUploadContainer = document.getElementById('upload-container');
const domFileInput = document.getElementById('fileInput');
const domFileNum = document.getElementById('fileNum');
const domFileList = document.getElementById('file-list');
const btnStartUpload = document.getElementById('btn-start-upload');
const btnClose = document.getElementById('btn-close');
let files = [];
domFileInput.onchange = () => {
    files = domFileInput.files;
    let lines = domFileList.children;
    while (lines[0]) {
        lines[0].remove();
    }
    if (files.length === 0) {
        domFileNum.value = ""
    } else {
        domFileNum.value = `已选择${files.length}个文件`;
        for (let i = 0; i < files.length; i++) {
            let line = document.createElement('div');
            line.setAttribute('class', 'file-view-line');
            line.innerHTML = `<div class="file-name"title="文件名：${files[i].name}">${files[i].name}</div><div class="file-size"title="文件大小：${files[i].size}字节">${formatFileSize(files[i].size)}</div><div class="file-state">等待上传</div>`;
            line.onclick = () => {
                let info = `${files[i].name}\n${files[i].size}字节`;
                Toast.info(info);
            }
            domFileList.appendChild(line);
        }
    }
}

btnStartUpload.onclick = () => {
    if (files.length === 0) {
        Toast.warning('请选择文件！');
        return;
    }
    btnStartUpload.disabled = domFileInput.disabled = true;
    let frameSize = 1024 * 150;
    const states = document.getElementsByClassName('file-state');
    let i = 0;
    let nextFile = true;
    let fileInterval = setInterval(() => {
        if (i >= files.length) {
            clearInterval(fileInterval);
            fileInterval = null;
            btnStartUpload.disabled = domFileInput.disabled = false;
            Toast.info('上传成功，请刷新页面！');
            // location.reload(true);
            return;
        }
        if (nextFile) {
            nextFile = false;
            uploadFile(files[i], frameSize, (progress) => {
                states[i].innerText = `${progress}%`;
            }, () => {
                nextFile = true;
                i++;
            }, (reason) => {
                clearInterval(fileInterval);
                fileInterval = null;
                btnStartUpload.disabled = domFileInput.disabled = false;
                Toast.error(reason);
                // location.reload(true);
            });
        }
    }, 1000);
}
btnUploadDlg.onclick = () => {
    fadein(domUploadContainer);
}
btnClose.onclick = () => {
    fadeout(domUploadContainer);
}